package cn.hxzy.assignperson.service.impl;

import cn.hxzy.assignperson.mapper.TeacherMajorMapper;
import cn.hxzy.assignperson.service.TeacherMajorService;
import cn.hxzy.common.domain.*;
import cn.hxzy.common.domain.ClassTable;
import cn.hxzy.common.domain.ClassTeacher;
import cn.hxzy.common.domain.TeacherMajor;
import cn.hxzy.common.domain.vo.*;
import cn.hxzy.assignperson.service.TeacherMajorService;
import cn.hxzy.common.domain.TeacherMajor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TeacherMajorServiceImpl implements TeacherMajorService {

    @Autowired
    private TeacherMajorMapper teacherMajorMapper;

    /**
     * 查询所有FuzeVo对象
     * @return FuzeVo对象列表
     */
    @Override
    public List<FuzeVo> selectAllGl() {
        List<FuzeVo> teacherMajors = teacherMajorMapper.selectAllGl();
        return teacherMajors;
    }

    /**
     * 根据ID查询InsertVo对象
     * @param id 要查询的ID
     * @return InsertVo对象
     */
    @Override
    public InsertVo selectByIdall(Integer id) {
        return teacherMajorMapper.selectByIdall(id);
    }

    /**
     * 查询所有School对象
     * @return School对象列表
     */
    @Override
    public List<School> selectAllSchool() {
        return teacherMajorMapper.selectAllSchool();
    }

    /**
     * 插入用户信息并关联专业
     * @param insertVo 插入的用户信息
     * @return 操作结果（1表示成功）
     */
    @Override
    public int insertUser(InsertVo insertVo) {
        // 新增之后获取新增之后的id
        teacherMajorMapper.insertUser(insertVo);
        int userId = insertVo.getUserId();
        System.out.println("-----------userId " + userId);
        teacherMajorMapper.insertTeacherMajor(userId, insertVo.getMajorId());
        return 1;
    }

    /**
     * 更新用户信息和专业信息
     * @param insertVo 更新的用户信息
     * @return 操作结果（1表示成功）
     */
    @Override
    public int updateUser(InsertVo insertVo) {
        teacherMajorMapper.updateUser(insertVo);
        teacherMajorMapper.updateMajor(insertVo);
        return 1;
    }

    /**
     * 删除教师专业关联信息和用户信息
     * @param id 要删除的ID
     * @return 操作结果（1表示成功）
     */
    @Override
    public int deleteTeacherMajor(Integer id) {
        teacherMajorMapper.deleteTeacherMajor(id);
        teacherMajorMapper.deleteUser(id);
        return 1;
    }

    /**
     * 根据专业ID查询所有老师
     * @param mid 专业ID
     * @return User对象列表
     */
    @Override
    public List<User> selectAllTeacher(Integer mid) {
        ArrayList<User> users = new ArrayList<>();
        // 先去中间表查询老师的集合
        List<Integer> teacherIds = teacherMajorMapper.selectTeachersId(mid);

        for (Integer teacherId : teacherIds) { // 循环老师id集合查询老师的id和姓名
            User user = teacherMajorMapper.selectById(teacherId);
            users.add(user);
        }

        return users;
    }

    /**
     * 查询教师的专业分组信息
     * @return TeacherVo01对象列表
     */
    @Override
    public List<TeacherVo01> selectteacherGl() {
        List<TeacherVo01> teacherVo01s = new ArrayList<>();

        List<Direction> directions = teacherMajorMapper.selectAllDirection();
        for (Direction direction : directions) {
            TeacherVo01 tv = new TeacherVo01();
            tv.setDirection(direction);
            Integer tid = direction.getDirectionId(); // 专业id
            System.out.println("directionId============" + tid);

            TeacherMajor teacherMajors = teacherMajorMapper.selectteacherGl(tid);
            System.out.println("teacherMajors============001" + teacherMajors);
            if (teacherMajors != null) {
                int teacherId = teacherMajors.getTeacherId();
                System.out.println("teacherId=========002" + teacherId);
                User user = teacherMajorMapper.selectTeacherNames(teacherId);
                String nickName = user.getNickName();
                tv.setNickName(nickName);
                tv.setUserId(teacherId);
            }
            teacherVo01s.add(tv);
        }
        System.out.println("000000000000000000000000000000001" + teacherVo01s);
        return teacherVo01s;
    }

    /**
     * 添加新的方向
     * @param directionName 方向名称
     * @return 操作结果（1表示成功）
     */
    @Override
    public int addDirection(String directionName) {
        return teacherMajorMapper.addDirection(directionName);
    }

    /**
     * 更新方向信息
     * @param direction 更新的方向信息
     * @return 操作结果（1表示成功）
     */
    @Override
    public int updateDirection(Direction direction) {
        return teacherMajorMapper.updateDirection(direction);
    }

    /**
     * 指定教研组
     * @param userId 用户ID
     * @param mid 专业ID
     */
    @Override
    @Transactional
    public void updateTeacheringResearchId(Integer userId, Integer mid) {
        // 根据专业id首先清空所有的 老师的教研组
        teacherMajorMapper.updateAll(mid);
        // 通过老师的id新指定教研组
        teacherMajorMapper.updateTeacheringResearchId(userId);
    }

    /**
     * 删除教师专业关联信息和方向信息
     * @param id 要删除的ID
     * @return 操作结果（1表示成功）
     */
    @Override
    public int deleteTeacherMajord(Integer id) {
        TeacherMajor teacherMajor = teacherMajorMapper.selectteacherGls(id);
        if (teacherMajor == null) {
            teacherMajorMapper.deleteDirection(id);
        } else {
            teacherMajorMapper.deleteTeacherMajord(id);
            teacherMajorMapper.deleteDirection(id);
        }
        return 1;
    }

//管理员向上
//===============================================================================================================
//教研组组长向下

    @Override
    public List<ClassTableVo> selectAllClassByMarjorId(Integer id) {
        ArrayList<ClassTableVo> classTableVos = new ArrayList<>();

        List<ClassTable> classTables = teacherMajorMapper.selectAllClassByMarjorId(id);//根据专业查询班级集合

        for (ClassTable classTable : classTables) {//循环班级集合拿出班级id
            ClassTableVo classTableVo = new ClassTableVo(//初始化循环的Classtable对象中的数据
                    classTable.getClassId(),
                    classTable.getClassName(),
                    classTable.getCreateId(),
                    classTable.getCreateTime(),
                    classTable.getSchoolId()
            );//往前端传送数据
            ArrayList<TeacherVo> teacherVos = new ArrayList<>();

            StringBuilder teacherNameBuilder = new StringBuilder();
            Integer classId = classTable.getClassId();
            List<Integer> tids = teacherMajorMapper.selectTeacherNameByClassId(classId);// 根据班级id查询老师id
            for (Integer tid : tids) {
                // 根据老师id查询老师id 老师姓名
                TeacherVo teacherVo = teacherMajorMapper.selectTeacherMessage(tid);
                teacherVos.add(teacherVo);
//                if (teacherNameBuilder.length() > 0) {
//                    teacherNameBuilder.append(", ");
//                }
//                teacherNameBuilder.append(teacherName);
//
//                String teacherName1 = teacherNameBuilder.toString();
//                classTableVo.setClassTeacher(teacherName1);

            }
            classTableVo.setClassTeacher(teacherVos);

            classTableVos.add(classTableVo);

        }

        return classTableVos;
    }

    @Override
    public List<TeacherVo> selectteachers(Integer tid) {
        List<TeacherVo> teacherMessage = new ArrayList<>();
        //根据专业id查询老师id
        List<Integer> integers = teacherMajorMapper.selectTeacherIdByMajorId(tid);
        for (Integer integer : integers) {
            //根据老师id查询到老师的姓名
            String tname = teacherMajorMapper.selectTeacherNameByUserId(integer);
            TeacherVo teacherVo = new TeacherVo(integer, tname);//老师信息对象
            teacherMessage.add(teacherVo);
        }
        return teacherMessage;
    }


    //分配老师
    @Transactional
    @Override
    public Integer addOrUpdate(Map<String, Object> map) {
        List<Integer> teacherlist = (List<Integer>) map.get("teachersId");
        Integer classId = (Integer) map.get("classId");

        //首先清空班级分配的老师
        teacherMajorMapper.deleteTeachersInClass(classId);


        if (teacherlist == null || teacherlist.isEmpty()) {
            return 0; // 或者抛出异常，表示没有教师ID
        }

        List<ClassTeacher> classTeachers = new ArrayList<>();
        for (Integer teacher : teacherlist) {
            classTeachers.add(new ClassTeacher(classId, teacher));
        }

        Integer i = teacherMajorMapper.addTeachersInClass(classTeachers);

        return i;
    }

    //修改班级方法
    @Override
    public Integer addOneClass(ClassTable classTable) {
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期时间
        String formattedDateTime = now.format(formatter);

        classTable.setCreateTime(now);

        Integer i = teacherMajorMapper.addOneClass(classTable);
        return i;
    }

    //修改班级
    @Override
    public Integer updateOneClass(ClassTable classTable) {
        Integer i = teacherMajorMapper.updateOneClass(classTable);
        return i;
    }

    @Override
    public Direction selectDirectionById(Integer id) {
        return teacherMajorMapper.selectDirectionById(id);
    }


}
